import 'cesium/Source/Widgets/CesiumWidget/CesiumWidget.css'


window.model = {}
import * as Cesium from "cesium";
import data from "@/assets/data/poi.json";
// 根据经纬度，获取图层对象。
export function initEarth(eid,Cesium) {
  Cesium.Ion.defaultAccessToken='eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiI4ZjgyZDQ4NS03OWM1LTQ1ZGItOTM5Ny1lNWE1MGFhNWMxZDQiLCJpZCI6NjEzNzksImlhdCI6MTYyNjAxNzY1OX0.CjL_fy5aUohkFgkf1HNKDCC8a_eTLWNj35I6Oy3EvEw';
  let viewer = new Cesium.Viewer(eid, {
    baseLayerPicker: false,
    fullscreenButton: false,
    vrButton: false,
    geocoder: false,
    animation: false,
    homeButton: false,
    infoBox: false,
    sceneModePicker: false,
    selectionIndicator: false,
    enableCompass:true,
    timeline: false,
    navigationHelpButton: false,
    navigationInstructionsInitiallyVisible: false,
    creditContainer: document.createElement('div'),
    contextOptions: {
      webgl: {
        alpha: true,
        depth: false,
        stencil: true,
        antialias: true,
        premultipliedAlpha: true,
        preserveDrawingBuffer: true,
        failIfMajorPerformanceCaveat: true,
      },
      allowTextureFilterAnisotropic: true,
    },

    // 天空盒
    skyBox: new Cesium.SkyBox({
      sources: {
        positiveX: require('@/assets/skybox/tycho2t3_80_px.jpg'),
        negativeX: require('@/assets/skybox/tycho2t3_80_mx.jpg'),
        positiveY: require('@/assets/skybox/tycho2t3_80_py.jpg'),
        negativeY: require('@/assets/skybox/tycho2t3_80_my.jpg'),
        positiveZ: require('@/assets/skybox/tycho2t3_80_pz.jpg'),
        negativeZ: require('@/assets/skybox/tycho2t3_80_mz.jpg'),
      },
    }),
    terrainProvider : new Cesium.CesiumTerrainProvider({
      url : '/files/gc/',
    })
  })
  let options = {}
  // 用于在使用重置导航重置地图视图时设置默认视图控制。接受的值是Cesium.Cartographic 和 Cesium.Rectangle.
  options.defaultResetView = Cesium.Rectangle.fromDegrees(80, 22, 130, 50)
  // 用于启用或禁用罗盘。true是启用罗盘，false是禁用罗盘。默认值为true。如果将选项设置为false，则罗盘将不会添加到地图中。
  options.enableCompass = true
  // 用于启用或禁用缩放控件。true是启用，false是禁用。默认值为true。如果将选项设置为false，则缩放控件将不会添加到地图中。
  options.enableZoomControls = true
  // 用于启用或禁用距离图例。true是启用，false是禁用。默认值为true。如果将选项设置为false，距离图例将不会添加到地图中。
  options.enableDistanceLegend = false
  // 用于启用或禁用指南针外环。true是启用，false是禁用。默认值为true。如果将选项设置为false，则该环将可见但无效。
  options.enableCompassOuterRing = true
  // viewer.scene.globe.depthTestAgainstTerrain = true;
  return viewer;
}





export function  add3Dtiles(Cesium,viewer,url){
  let tilesetModel = new Cesium.Cesium3DTileset({
    url:url,
    dynamicScreenSpaceError : true,
    dynamicScreenSpaceErrorDensity : 0.00278,
    dynamicScreenSpaceErrorFactor : 4.0,
    dynamicScreenSpaceErrorHeightFalloff : 0.25,
    // minimumPixelSize: 128,
    maximumMemoryUsage:128,
    backFaceCulling:false
  });
  tilesetModel.readyPromise.then(function (argument) {
    let heightOffset = 0; // 调整倾斜摄影高度，防止飘和进入地下
    let boundingSphere = tilesetModel.boundingSphere;
    let cartographic =  Cesium.Cartographic.fromCartesian(boundingSphere.center);
    let surface = Cesium.Cartesian3.fromRadians(cartographic.longitude, cartographic.latitude, 0.0);
    let offset =  Cesium.Cartesian3.fromRadians(cartographic.longitude, cartographic.latitude, heightOffset);
    let translation =  Cesium.Cartesian3.subtract(offset, surface, new  Cesium.Cartesian3());
    tilesetModel.modelMatrix =  Cesium.Matrix4.fromTranslation(translation);
    // debugger
    viewer.scene.primitives.add(tilesetModel);
  });
  return tilesetModel
}



//三维添加对应地图
export function addLayersfor3d(Cesium,viewer,url){
  console.log(url)
  let provider = viewer.scene.imageryLayers.addImageryProvider(
      new Cesium.UrlTemplateImageryProvider({
        url: url
  }))
  return provider
}


export function addTianlayer(Cesium,viewer){
  var subdomains=['0','1','2','3','4','5','6','7'];
  let imgageProvider = viewer.imageryLayers.addImageryProvider(new Cesium.WebMapTileServiceImageryProvider({
    //影像底图
    url: "http://t{s}.tianditu.com/img_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=img&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default&format=tiles&tk=3a7fe2159cf7dec6c78c9bdfdedee810",
    subdomains: subdomains,
    layer: "tdtImgLayer",
    style: "default",
    format: "image/jpeg",
    tileMatrixSetID: "GoogleMapsCompatible",//使用谷歌的瓦片切片方式
    show: true
  }))
  viewer.imageryLayers.addImageryProvider(new Cesium.WebMapTileServiceImageryProvider({
    //影像注记
    url: "http://t{s}.tianditu.com/cia_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=cia&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default.jpg&tk=3a7fe2159cf7dec6c78c9bdfdedee810",
    subdomains: subdomains,
    layer: "tdtCiaLayer",
    style: "default",
    format: "image/jpeg",
    tileMatrixSetID: "GoogleMapsCompatible",
    show: true
  }));
  return imgageProvider;
}

//添加天地图矢量
export function addGdsllayer(Cesium,viewer){
  let tdtLayer = new Cesium.UrlTemplateImageryProvider({
    url: "http://webrd02.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}",
    minimumLevel: 3,
    maximumLevel: 18
  })
  let imgageProvider =  viewer.imageryLayers.addImageryProvider(tdtLayer);
  return imgageProvider
}



export function addPoint(Cesium,viewer,lon,lat,pid){
  //添加中心点
  var x=1;
  var flog=true;
  viewer.entities.remove(viewer.entities.getById(pid));
  viewer.entities.remove(viewer.entities.getById(`${pid}外部`));
  viewer.entities.add({
    id:pid,
    name:"圆点point闪烁",
    position:Cesium.Cartesian3.fromDegrees(lon,lat,20),
    point : {
      show : true, // default
      color :new Cesium.CallbackProperty(function () {
        if(flog){
          x=x-0.05;
          if(x<=0){
            flog=false;
          }
        }else{
          x=x+0.05;
          if(x>=1){
            flog=true;
          }
        }
        // return Cesium.Color.CYAN.withAlpha(x);
        return Cesium.Color.fromCssColorString(`rgb(252,0,0,${x})`)
      },false),
      pixelSize : 10, // default: 1
      // outlineWidth :10
      outlineWidth :0
    }
  });
  viewer.entities.add({
    id:`${pid}外部`,
    name:"圆点point闪烁",
    position:Cesium.Cartesian3.fromDegrees(lon,lat,20),
    point : {
      show : true, // default
      color :new Cesium.CallbackProperty(function () {
        if(flog){
          x=x-0.05;
          if(x<=0){
            flog=false;
          }
        }else{
          x=x+0.05;
          if(x>=1){
            flog=true;
          }
        }
        return Cesium.Color.fromCssColorString('rgb(128,128,128)')
      },false),
      pixelSize : 20, // default: 1
      // outlineWidth :10
      outlineWidth :0
    }
  });
}





//加载多块3dtiles数据
export function add3Dtilesforarray(Cesium,viewer,modelArray){
  debugger
  let Allpaths = []; //url path
  let tilesetModel = []; //export models
  modelArray.forEach((ite)=>{
    Allpaths.push(ite.url);
  })
  const translation = new Cesium.Cartesian3(
      -1.398521324920626,
      0.7823052871729486,
      0.7015244410592609
  );
  for(let i=0; i<modelArray.length;i++){

    // let l = new Cesium.Cesium3DTileset({
    //   url: modelArray[i].url,//这里是模型地址
    //   maximumScreenSpaceError: 1
    // });
    // //这里是移动的距离
    // const tx = 0;
    // const ty = 0;
    // const tz = 120;
    // l.readyPromise.then(function (argument) {
    //   viewer.scene.primitives.add(l);
    //   const cartographic = Cesium.Cartographic.fromCartesian(
    //       l.boundingSphere.center
    //   );
    //   const surface = Cesium.Cartesian3.fromRadians(
    //       cartographic.longitude,
    //       cartographic.latitude,
    //       cartographic.height
    //   );
    //   const m = Cesium.Transforms.eastNorthUpToFixedFrame(surface);
    //
    //   //平移
    //   const _tx = tx ? tx : 0;
    //   const _ty = ty ? ty : 0;
    //   const _tz = tz ? tz : 0;
    //   const tempTranslation = new Cesium.Cartesian3(_tx, _ty, _tz);
    //   const offset = Cesium.Matrix4.multiplyByPoint(
    //       m,
    //       tempTranslation,
    //       new Cesium.Cartesian3(0, 0, 0)
    //   );
    //   const translation = Cesium.Cartesian3.subtract(
    //       offset,
    //       surface,
    //       new Cesium.Cartesian3()
    //   );
    //   l.modelMatrix = Cesium.Matrix4.fromTranslation(translation);
    //   viewer.zoomTo(l);
    // });




    viewer.entities.add({
      name: modelArray[i].text,
      id:modelArray[i].id,
      position: Cesium.Cartesian3.fromDegrees( Number(modelArray[i].longitude),Number(modelArray[i].dimension), 10.0),
      billboard: { //图标
        image: '/images/poi.png',
        width:25,
        height: 125,
        verticalOrigin:  Cesium.VerticalOrigin.Bottom
      },
    });
    tilesetModel.push({
      id:modelArray[i].id,
      lon:modelArray[i].longitude,
      lat:modelArray[i].dimension,
      text:modelArray[i].text,
      model:new Cesium.Cesium3DTileset({
        url:modelArray[i].url,
        loadSiblings: true, // 如果为true则不会在已加载完概况房屋后，自动从中心开始超清化房屋
        cullRequestsWhileMovingMultiplier: 10, // 值越小能够更快的剔除
        preloadWhenHidden: true,
        preferLeaves: true,
        maximumMemoryUsage: 128, // 内存分配变小有利于倾斜摄影数据回收，提升性能体验
        progressiveResolutionHeightFraction: 0.5, // 数值偏于0能够让初始加载变得模糊
        dynamicScreenSpaceErrorDensity: 0.1, // 数值加大，能让周边加载变快
        dynamicScreenSpaceErrorFactor: 1, // 不知道起了什么作用没，反正放着吧先
        dynamicScreenSpaceError: true // 根据测试，有了这个后，会在真正的全屏加载完之后才清晰化房屋
      })
    })
  }
  tilesetModel.forEach((ite)=>{
    ite.model.modelMatrix = Cesium.Matrix4.fromTranslation(translation);
    ite.model.readyPromise.then(function (clampedCartesians) {
      //options
      let heightOffset = 25; // 调整倾斜摄影高度，防止飘和进入地下
      let boundingSphere = ite.model.boundingSphere;
      let cartographic =  Cesium.Cartographic.fromCartesian(boundingSphere.center);
      let surface = Cesium.Cartesian3.fromRadians(cartographic.longitude, cartographic.latitude, 0.0);
      let offset =  Cesium.Cartesian3.fromRadians(cartographic.longitude, cartographic.latitude, heightOffset);
      let translation =  Cesium.Cartesian3.subtract(offset, surface, new  Cesium.Cartesian3());
      ite.model.modelMatrix =  Cesium.Matrix4.fromTranslation(translation);
      //添加对应的模型组
      viewer.scene.primitives.add(ite.model);
      // viewer.zoomTo(ite)
    })
  })
  return tilesetModel
}




//加载白膜数据
export function loadTilesShader(Cesium,viewer,o,status) {
  if(status){
    viewer.scene.globe.enableLighting = true//必须开启光照效果，
    let tileset =  null;
    tileset = viewer.scene.primitives.add(
        new Cesium.Cesium3DTileset({
          url:'/files/bm/tileset.json'
        }),
    );
    tileset.readyPromise.then((tile) => {
      //定位
      let boundingSphere = tile.boundingSphere;
      viewer.camera.lookAtTransform(Cesium.Matrix4.IDENTITY);
      //更改着色器代码
      tile.tileVisible.addEventListener(function (res) {
        let content = res.content;
        let featuresLength = content.featuresLength;
        for (let i = 0; i < featuresLength; i += 2) {
          let feature = content.getFeature(i);
          let model = feature.content._model;
          if (model && model._pipelineResources) {
            let program = model._pipelineResources[1];
            // const color = `vec4(0,127.5/255.,1.,1.)`;
            const color = `vec4(0,127.5/255.,1.,1.)`;
            program._fragmentShaderSource.sources[0] = `
							uniform vec2 model_iblFactor;
							uniform mat3 model_iblReferenceFrameMatrix;
							uniform float model_luminanceAtZenith;
							uniform float u_metallicFactor;
							uniform float u_roughnessFactor;
							uniform int model_featuresLength;
							uniform sampler2D model_batchTexture;
							uniform vec4 model_textureStep;
							uniform float model_colorBlend;
							uniform bool model_commandTranslucent;
							uniform sampler2D model_pickTexture;
							varying vec3 v_positionWC;
							varying vec3 v_positionEC;
							varying vec3 v_normalEC;
							varying vec3 v_positionMC;
							varying float v_featureId_0;
							struct SelectedFeature
							{
								int id;
								vec2 st;
								vec4 color;
							};
							struct FeatureIds
							{
								int featureId_0;
							};
							vec2 computeSt(float featureId)
							{
								float stepX = model_textureStep.x;
								float centerX = model_textureStep.y;

								#ifdef MULTILINE_BATCH_TEXTURE
								float stepY = model_textureStep.z;
								float centerY = model_textureStep.w;

								float xId = mod(featureId, model_textureDimensions.x); 
								float yId = floor(featureId / model_textureDimensions.x);
								
								return vec2(centerX + (xId * stepX), centerY + (yId * stepY));
								#else
								return vec2(centerX + (featureId * stepX), 0.5);
								#endif
							}
							void selectedFeatureIdStage(out SelectedFeature feature, FeatureIds featureIds)
							{   
								int featureId = featureIds.SELECTED_FEATURE_ID;
								if (featureId < model_featuresLength)
								{
									vec2 featureSt = computeSt(float(featureId));

									feature.id = featureId;
									feature.st = featureSt;
									feature.color = texture2D(model_batchTexture, featureSt);
								}
								else
								{
									feature.id = model_featuresLength + 1;
									feature.st = vec2(0.0);
									feature.color = vec4(1.0);
								}

								#ifdef HAS_NULL_FEATURE_ID
								if (featureId == model_nullFeatureId) {
									feature.id = featureId;
									feature.st = vec2(0.0);
									feature.color = vec4(1.0);
								}
								#endif
							}
							SelectedFeature selectedFeature;
							void main(){
								vec4 position = czm_inverseModelView * vec4(v_positionEC,1.);//获取模型的世界坐标
								float buildMaxHeight = 70.0;//建筑群最高高度 配渐变色
								gl_FragColor = ${color};//赋予基础底色
								gl_FragColor *= vec4(vec3(position.y / buildMaxHeight ), 1.0);//根据楼层高度比例渲染渐变色
								float time = abs(fract(czm_frameNumber / 360.0)-0.5)*2.;//动画频率 约束在(0,1) 更改频率修改360.0
								float diffuse = step(0.005, abs(clamp(position.y / buildMaxHeight, 0.0, 1.0) - time));//根据帧数变化,光圈颜色白色,由底部朝上一丢丢(0.05)开始逐渐上移显现.
								gl_FragColor.rgb += gl_FragColor.rgb * (1.0 - diffuse );//单纯叠加颜色 感兴趣的可以mix混合下
							}
						`;
          }
        }
      });
    })
    window.model[o.id]  = tileset;
    return tileset
  }else{
    viewer.scene.primitives.remove(window.model[o.id]);
  }
}


//路网
export function appendRoads(Cesium,viewer,o,status){
  if(status){
    var promise = Cesium.GeoJsonDataSource.load('/data/luwang.json');  //显示管线数据  直接加载json数据 比把json转化成czml在加载 快很多
    promise.then(function (dataSource) {
      viewer.dataSources.add(dataSource);
      var entities = dataSource.entities.values;
      var colorHash = {};

      for (var o = 0; o < entities.length; o++) {
        var r = entities[o];
        r.nameID = o;   //给每条线添加一个编号，方便之后对线修改样式
        r.polyline.width = 10;  //添加默认样式
        (r.polyline.material = new Cesium.PolylineGlowMaterialProperty({
          glowPower: .1, //一个数字属性，指定发光强度，占总线宽的百分比。
          color: Cesium.Color.ORANGERED.withAlpha(.9)
        }), 10)

      }
      var temp = new Array();
      window.Hightlightline = function (nameid) {
        var exists = temp.indexOf(nameid);
        if (exists <= -1) {
          Highlight(nameid,50, 50);
          temp.push(nameid);  // 添加线nameID到数组，
        }
        else  //已经是高亮状态了 再次点击修改为原始状态
        {
          Highlight(nameid,10, 10);
          temp.splice(exists, 1);  //删除对应的nameID
        }
      }
      window.Highlight = function (nameid,width1, width2) {
        for (var o = 0; o < entities.length; o++) {
          var m = entities[o];
          if (nameid == o) {
            m.polyline.width = width1;
            (m.polyline.material = new Cesium.PolylineGlowMaterialProperty({
              glowPower: .1, //一个数字属性，指定发光强度，占总线宽的百分比。
              color: Cesium.Color.ORANGERED.withAlpha(.9)
            }), width2)
          }
        }
      }
    });
    viewer.flyTo(promise);
    viewer.screenSpaceEventHandler.setInputAction(function onLeftClick(movement) {
      var pickedFeature = viewer.scene.pick(movement.position);
      if (typeof (pickedFeature) != "undefined")   //鼠标是否点到线上
      {
        var name_id = pickedFeature.id.nameID;  //获取每条线的nameID
        Hightlightline(name_id);
      }
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
  }else{
    viewer.dataSources.removeAll()
  }
}
//地铁
export function appendditie(Cesium,viewer,o,status){

  if(status){
    let temp = o;
    // viewer.dataSources.removeAll(); //移除
    var promise = Cesium.GeoJsonDataSource.load('/data/ditie.json');  //显示管线数据  直接加载json数据 比把json转化成czml在加载 快很多
    // window.model[temp.id] =promise;
    promise.then(function (dataSource) {
      console.log(temp)
      viewer.dataSources.add(dataSource);
      var entities = dataSource.entities.values;
      var colorHash = {};

      for (var o = 0; o < entities.length; o++) {
        var r = entities[o];
        r.nameID = o;   //给每条线添加一个编号，方便之后对线修改样式
        r.polyline.width = 10;  //添加默认样式
        (r.polyline.material = new Cesium.PolylineGlowMaterialProperty({
          glowPower: .1, //一个数字属性，指定发光强度，占总线宽的百分比。
          color: Cesium.Color.ORANGERED.withAlpha(.9)
        }), 10)

      }
      var temp = new Array();
      window.Hightlightline = function (nameid) {
        var exists = temp.indexOf(nameid);
        if (exists <= -1) {
          Highlight(nameid,50, 50);
          temp.push(nameid);  // 添加线nameID到数组，
        }
        else  //已经是高亮状态了 再次点击修改为原始状态
        {
          Highlight(nameid,10, 10);
          temp.splice(exists, 1);  //删除对应的nameID
        }
      }
      window.Highlight = function (nameid,width1, width2) {
        for (var o = 0; o < entities.length; o++) {
          var m = entities[o];
          if (nameid == o) {
            m.polyline.width = width1;
            (m.polyline.material = new Cesium.PolylineGlowMaterialProperty({
              glowPower: .1, //一个数字属性，指定发光强度，占总线宽的百分比。
              color: Cesium.Color.ORANGERED.withAlpha(.9)
            }), width2)
          }
        }
      }
      return dataSource
    });
    viewer.flyTo(promise);
    viewer.screenSpaceEventHandler.setInputAction(function onLeftClick(movement) {
      var pickedFeature = viewer.scene.pick(movement.position);
      if (typeof (pickedFeature) != "undefined")   //鼠标是否点到线上
      {
        var name_id = pickedFeature.id.nameID;  //获取每条线的nameID
        Hightlightline(name_id);
      }
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
  }else{
    viewer.dataSources.removeAll()
  }
}


//poi点
export function addPoipoint(Cesium,viewer,status) {
  if(status){
    let data = require('@/assets/data/poi.json');
    console.log(data)
    data.features.forEach((ite)=>{
      addPoint(Cesium,viewer,Number(ite.geometry.coordinates[0]),Number(ite.geometry.coordinates[1]),ite.id)
    })
  }else{
    let data = require('@/assets/data/poi.json');
    console.log(data)
    data.features.forEach((ite)=>{
      viewer.entities.remove(viewer.entities.getById(ite.id));
      viewer.entities.remove(viewer.entities.getById(`${ite.id}外部`));
    })

  }


}



export async function addGeojson(Cesium,viewer,o,status) {
  if(status){
    let res = await Cesium.GeoJsonDataSource.load(o.remark, {
      stroke: Cesium.Color.WHITE,
      fill: Cesium.Color.ORANGE.withAlpha(0.3), //注意：颜色必须大写，即不能为blue
      strokeWidth: 5
    });
    viewer.dataSources.add(res);
  }else {
    viewer.dataSources.removeAll(); //移除
  }


}



//2d影像
export function add2dLayers(Cesium,viewer,o) {
  let img_arcgis= new Cesium.UrlTemplateImageryProvider({
    url:o.url
  });
  let imagesLayer = viewer.scene.imageryLayers.addImageryProvider(img_arcgis)
  return imagesLayer
}
